package com.ebelter.temperaturegun.ui.activity;


import android.app.Activity;
import android.app.Dialog;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import com.ebelter.btcomlib.CommonLib;
import com.ebelter.btcomlib.models.beans.UpdateVersionBean;
import com.ebelter.btcomlib.models.bluetooth.base.BlueManager;
import com.ebelter.btcomlib.models.bluetooth.bean.ProductStyle;
import com.ebelter.btcomlib.models.bluetooth.interfaces.IBlueStationListener;
import com.ebelter.btcomlib.models.bluetooth.products.ear_temperature.EarTemperatureConstant;
import com.ebelter.btcomlib.models.bluetooth.products.temperature.TemperatureConstant;
import com.ebelter.btcomlib.models.bluetooth.products.temperature2.Temperature2Constant;
import com.ebelter.btcomlib.models.bluetooth.products.temperature2.Temperature2Manager;
import com.ebelter.btcomlib.models.bluetooth.products.temperature2.bean.TemMesureResult2;
import com.ebelter.btcomlib.models.bluetooth.products.temperature2.bean.TemMesureResult2His;
import com.ebelter.btcomlib.models.bluetooth.products.temperature2.interfaces.Temperature2MesureResult;
import com.ebelter.btcomlib.models.eventbus.CommonEventBus;
import com.ebelter.btcomlib.models.https.NetUtils;
import com.ebelter.btcomlib.models.https.interfaces.HttpResponse;
import com.ebelter.btcomlib.models.https.responses.GetTempertureData;
import com.ebelter.btcomlib.utils.AppUtils;
import com.ebelter.btcomlib.utils.NumUtils;
import com.ebelter.btcomlib.utils.StringUtils;
import com.ebelter.btcomlib.utils.TimeUtils;
import com.ebelter.btcomlib.utils.ToastUtil;
import com.ebelter.btcomlib.utils.UserSpUtil;
import com.ebelter.btcomlib.utils.ViewUtils;
import com.ebelter.btcomlib.utils.activity_manager.ActivityManagers;
import com.ebelter.btcomlib.utils.log.LogUtils;
import com.ebelter.btcomlib.views.ListViewForScrollView;
import com.ebelter.btcomlib.views.dialogs.TextTipDialog;
import com.ebelter.temperaturegun.R;
import com.ebelter.temperaturegun.TAppConfig;
import com.ebelter.temperaturegun.adapters.MainHisLvAdapter;
import com.ebelter.temperaturegun.model.TgManager;
import com.ebelter.temperaturegun.model.app.IConstant;
import com.ebelter.temperaturegun.model.app.TemUtils;
import com.ebelter.temperaturegun.model.http.TGNetUtils;
import com.ebelter.temperaturegun.model.http.TemUpdateService;
import com.ebelter.temperaturegun.model.http.TgUpLoadDataUtil;
import com.ebelter.temperaturegun.utils.TemGunUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class MainActivity extends TBaseActivity implements View.OnClickListener {

    public static final String TAG = "MainActivity";
    private static final String N = "--";

    private TextView main_login_userName_tv;//用户名字
    private TextView main_time_tv;//时间
    private LinearLayout m_result_ll;
    private TextView main_zwshj_tv;//暂无数据
    private ImageView main_bl_connect_flag_iv;//蓝牙连接的标志
    private ImageView main_wenduweizhi_flag_iv;//温度位置
    private TextView main_wendu_value_tv;//测量温度数值显示
    private TextView main_warring_tv;//警告温度
    private TextView m_mesure_station_tv;//测量状态
    private TextView m_bishangci_tv;//比上次
    private ImageView m_jqqsh_iv;//近期趋势
    private TextView main_wendu_unit_tv;//温度模式


    private TextView main_norecord_tv;//暂无记录
    private ListViewForScrollView main_lv;//暂无记录
    private MainHisLvAdapter mMainHisLvAdapter;

    private TextView nomore_tv;

    private ScrollView m_sv;



    private void FV() {
        main_login_userName_tv = findViewById(R.id.main_login_userName_tv);
        main_time_tv = findViewById(R.id.main_time_tv);
        m_result_ll = findViewById(R.id.m_result_ll);
        main_zwshj_tv = findViewById(R.id.main_zwshj_tv);
        main_wenduweizhi_flag_iv = findViewById(R.id.main_wenduweizhi_flag_iv);
        main_bl_connect_flag_iv = findViewById(R.id.main_bl_connect_flag_iv);
        main_wendu_value_tv = findViewById(R.id.main_wendu_value_tv);
        main_warring_tv = findViewById(R.id.main_warring_tv);
        m_mesure_station_tv = findViewById(R.id.m_mesure_station_tv);
        m_bishangci_tv = findViewById(R.id.m_bishangci_tv);
        main_norecord_tv = findViewById(R.id.main_norecord_tv);
        main_wendu_unit_tv = findViewById(R.id.main_wendu_unit_tv);
        m_jqqsh_iv = findViewById(R.id.m_jqqsh_iv);
        m_sv = findViewById(R.id.m_sv);

        main_lv = findViewById(R.id.main_lv);
        nomore_tv = findViewById(R.id.nomore_tv);

        mMainHisLvAdapter = new MainHisLvAdapter(this);
        main_lv.setAdapter(mMainHisLvAdapter);

        main_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (mMainHisLvAdapter!=null){
                    GetTempertureData.ResultDataBean.DataBean dataBean = mMainHisLvAdapter.getDatas().get(position);
                    DetailShowActivity.openDetailShowActivity(MainActivity.this,dataBean.testDate,dataBean.tempType,dataBean.temperature);
                }
            }
        });


        m_sv.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
               // LogUtils.i(TAG,"----onScrollChange---getMeasuredHeight="+v.getMeasuredHeight()+"--scrollX="+scrollX+"--scrollY="+scrollY+"--oldScrollX="+oldScrollX+"--oldScrollY="+oldScrollY);

                View view = m_sv.getChildAt(m_sv.getChildCount()-1);
                int d = view.getBottom();
                d -= (m_sv.getHeight()+m_sv.getScrollY());
                if(d==0){
                    LogUtils.i(TAG,"滑到到底部了");
                    if (System.currentTimeMillis()-lastLoadingTime > 3000){
                        LogUtils.i(TAG,"---------加载更多");
                        lastLoadingTime = System.currentTimeMillis();
                        if (!TAppConfig.isVisitorModel){
                            getButtomValue();
                        }

                    }
                }


            }
        });



    }

    private long lastLoadingTime;




    //这个MyReceiver主要监测时间的变化
    private MyReceiver myReceiver;

    private TgManager mTgManager;


    @Override
    protected int setContentViewId() {
        return R.layout.activity_main;
    }


    @Override
    protected void initView() {
        FV();
        tryOpenBluetooth();

        addBluetoothStatusLis();
    }

    //添加蓝牙状态监听器
    private void addBluetoothStatusLis() {
        BlueManager.getInstance().addBluetoothStationListener(mIBlueStationListener);
    }

    private IBlueStationListener mIBlueStationListener = new IBlueStationListener() {
        @Override
        public void STATE_OFF() {
            ToastUtil.show(CommonLib.getString(R.string.close_blue_tip));//打开蓝牙提示语
        }
        @Override
        public void STATE_TURNING_OFF() {}
        @Override
        public void STATE_ON() {}
        @Override
        public void STATE_TURNING_ON() {}
    };



    private void tryOpenBluetooth() {
        if (!BlueManager.getInstance().isBluetoothOpen()){
            BlueManager.getInstance().openBluetooth3(this);
        }
    }

    @Override
    protected void initData() {
        EventBus.getDefault().register(this);
        registerReceiver();//时间变化监听器
        disUserName(); //显示用户名
        timeChange();//显示时间
        updateWarringUnit();//更新警告温度
        updateUnitMode();//更新温度的模式



        mTgManager=new TgManager(this);
        setListeners();
        mTgManager.startWork();

        if (!TAppConfig.isVisitorModel){
            getButtomValue();
        }


        getNetVersion();

    }

    public void getNetVersion() {
        if (NetUtils.available()){
            final int verCode= AppUtils.getVersionCode(this);//获取当前版本号
            LogUtils.i(TAG,"verCode---" + verCode);
            TGNetUtils.getInstance().getUpdateVersionJson(this, new HttpResponse<UpdateVersionBean>() {
                @Override
                public void result(boolean isRequestSuccess, String requestDes, UpdateVersionBean updateVersionBean, String s) {
                    LogUtils.i(TAG,"s---"+s);
                    if (isRequestSuccess&&updateVersionBean!=null){

                        LogUtils.i(TAG,"服务器上的json--"+updateVersionBean.toString());
                        if (NumUtils.string2Int(updateVersionBean.getVerCode())>verCode){

                            showUpdateDialog(MainActivity.this,updateVersionBean);
                        }
                    }
                }
            });
        }
    }


    private TextTipDialog updateDialog;
    private void showUpdateDialog(Activity activity, final UpdateVersionBean mUpdateVersionBean) {
        if (activity==null||activity.isFinishing()||activity.isDestroyed()||mUpdateVersionBean==null){
            return;
        }

        if (updateDialog!=null){
            updateDialog.cancel();
            updateDialog=null;
        }

        updateDialog=new TextTipDialog(activity, StringUtils.getResStr(R.string.New_version_is_available_touch_to_update));
        updateDialog.isPingBiBack=true;
        updateDialog.show();
        // dialog.setNativebtVisibility(View.GONE);
        updateDialog.setPositive_btBg(R.drawable.sp_s0176ff_r6);
        updateDialog.setListener(new TextTipDialog.ICancelOkBtListener() {
            @Override
            public void cancel(Dialog dialogView) {
                dialogView.cancel();
            }
            @Override
            public void ok(Dialog dialogView) {
                dialogView.cancel();
                update(mUpdateVersionBean);
            }
        });
    }

    //更新按钮
    private void update(UpdateVersionBean mUpdateVersionBean) {
        if (!NetUtils.available()){
            ToastUtil.show(R.string.Network_error);
            return;
        }
        if (mUpdateVersionBean==null){
            return;
        }

        Intent updateIntent = new Intent(this,TemUpdateService.class);
        updateIntent.putExtra(TemUpdateService.DownloadSer,mUpdateVersionBean);
        startService(updateIntent);

    }

    //更新温度的模式
    private void updateUnitMode() {
        int model = TemUtils.getUerUnit();
        ViewUtils.setTextViewStr(main_wendu_unit_tv,model==0?"°C":"°F");

        if (mMainHisLvAdapter!=null){
            mMainHisLvAdapter.notifyUnit();
        }
    }

    //更新警告温度
    private void updateWarringUnit() {
        float warring = TemUtils.getUerWarringUnit();
        ViewUtils.setTextViewStr(main_warring_tv, NumUtils.numBaoLiuWei1(warring)+"°C");
    }

    private void setListeners() {
        mTgManager.setMesuresCalBack(new Temperature2MesureResult(){
            @Override
            public void mesureResult(TemMesureResult2 result) {
                LogUtils.i(TAG,"-----接收到测量数据 = "+result.toString());
                disMesureData(result);
                //mTgManager.setUnitC();
            }

            @Override
            public void mesureHisResult(TemMesureResult2His hisResult) {


            }

            @Override
            public void error(String bluetoothName,int errorCode) {
                LogUtils.i(TAG,"-----接收到测量错误 error = "+errorCode+"--bluetoothName= "+bluetoothName);


                if (EarTemperatureConstant.EarTemperature_NAME.equals(bluetoothName)){
                    if (errorCode==1){
                        ToastUtil.show(CommonLib.getString(R.string.str_wenduguodi));
                    }
                }
            }

            @Override
            public void onDevicePoweroff() {
                LogUtils.i(TAG,"-----接收到关机信息");
            }

            @Override
            public void setUnitSuccess() {
                LogUtils.i(TAG,"-----接收到单位更改成功信息");

                if (UnitSwitchActivity.isResume){
                    ActivityManagers.getInstance().closeActivity(UnitSwitchActivity.TAG);
                    ToastUtil.show(CommonLib.getString(R.string.qhdwchg));
                }

                CommonEventBus commonEventBus = new CommonEventBus(TAG,SettingActivity.TAG,1,"更新一下显示单位");
                EventBus.getDefault().post(commonEventBus);


            }

            @Override
            public void getHisDataFinish() {
                LogUtils.i(TAG,"-----获取历史数据完成");
            }

            @Override
            public void getVersion(int versionCode) {
                LogUtils.i(TAG,"-----获取版本信息 versionCode="+versionCode);
            }

            @Override
            public void onConnected(ProductStyle productStyle, BluetoothDevice device) {
                LogUtils.i(TAG,"-----连接成功 device = "+device.getAddress()+"---"+device.getName());
                ViewUtils.setImageResource(main_bl_connect_flag_iv,R.drawable.ic_bl_connected);
                //sendUnit2Scale();//连接成功以后把app的单位下发给称


                if (Temperature2Constant.Temperature2_NAME.equals(device.getName())){
                    int unit = UserSpUtil.readInt(IConstant.IUserSpCon.UNIT,0);//0C 1F
                    if (unit==0){
                        if (mTgManager!=null)mTgManager.setUnitC();
                    }else {
                        if (mTgManager!=null)mTgManager.setUnitF();
                    }
                }


            }

            @Override
            public void onConnecting(ProductStyle productStyle, BluetoothDevice device) {
                LogUtils.i(TAG,"-----正在连接 device = "+device.getAddress());
            }

            @Override
            public void onDisConnected(ProductStyle productStyle) {
                LogUtils.i(TAG,"-----连接已经断开");
                ViewUtils.setImageResource(main_bl_connect_flag_iv,R.drawable.ic_bl_unconnect);
            }


        });
        m_jqqsh_iv.setOnClickListener(this);
    }



    private static final String add = "+";
    private static final String nullstr = "";
    private String getFuHao(float val){
        if (val>0){
            return add;
        }
        return nullstr;
    }

    private TemMesureResult2 lastTemMesureResult2_erwen;
    private TemMesureResult2 lastTemMesureResult2_ewen;
    //显示测量数据
    private void disMesureData(TemMesureResult2 result) {

        if (result==null){
            return;
        }

        ViewUtils.displayView(m_result_ll);
        ViewUtils.hideView(main_zwshj_tv);

        float disTem = TemGunUtil.getDisTemC(result.temperature);

        //显示图标
        if (result.com==0||result.com==1){
            ViewUtils.setImageResource(main_wenduweizhi_flag_iv,R.drawable.ic_erwen);
        }else {
            ViewUtils.setImageResource(main_wenduweizhi_flag_iv,R.drawable.ic_ewen);
        }

        //显示状态 文字
        String status = TemUtils.getResultDesc(disTem);
        ViewUtils.setTextViewStr(m_mesure_station_tv,status);

        //00：耳温C标记
        //01：耳温F标记
        //02：额温C标记
        //03：额温F标记
        if (result.com==0||result.com==2){
            //C
            ViewUtils.setTextViewStr(main_wendu_value_tv,disTem + "");//显示温度  文字
            UserSpUtil.writeInt(IConstant.IUserSpCon.UNIT,0);

        }else {
            //F
            ViewUtils.setTextViewStr(main_wendu_value_tv,TemGunUtil.getDisTemF(result.temperature) + "");//显示温度  文字
            UserSpUtil.writeInt(IConstant.IUserSpCon.UNIT,1);

        }
        updateUnitMode();//刷新一下温度模式



        //00：耳温C标记
        //01：耳温F标记
        //02：额温C标记
        //03：额温F标记
        if (result.com==0||result.com==1){//耳温
            if (lastTemMesureResult2_erwen==null){//上一次的耳温没有数据就显示—-
                ViewUtils.setTextViewStr(m_bishangci_tv,N);
            }else {
                float t1=lastTemMesureResult2_erwen.temperature;
                if (result.com==0){
                    //C
                    float r1 = NumUtils.numBaoLiuWei1(disTem-TemGunUtil.getDisTemC(lastTemMesureResult2_erwen.temperature));
                    ViewUtils.setTextViewStr(m_bishangci_tv,getFuHao(r1)+r1+" °C");
                }else {
                    //F
                    double f1=TemGunUtil.getDisTemF(result.temperature);
                    double f2=TemGunUtil.getDisTemF(t1);
                    float r1 = NumUtils.numBaoLiuWei1((float) (f1-f2));
                    ViewUtils.setTextViewStr(m_bishangci_tv,getFuHao(r1)+r1+" °F");
                }
            }
            lastTemMesureResult2_erwen=result;
        }else{//额温
            if (lastTemMesureResult2_ewen == null){//上一次的额温没有数据就显示—-
                ViewUtils.setTextViewStr(m_bishangci_tv,N);
            }else {
                float t1=lastTemMesureResult2_ewen.temperature;
                if (result.com==2){
                    //C
                    float r1 = NumUtils.numBaoLiuWei1(disTem-TemGunUtil.getDisTemC(t1));;
                    ViewUtils.setTextViewStr(m_bishangci_tv,getFuHao(r1)+r1+" °C");
                }else {
                    //F
                    double f1 = TemGunUtil.getDisTemF(result.temperature);
                    double f2 = TemGunUtil.getDisTemF(t1);
                    float r1 = NumUtils.numBaoLiuWei1((float) (f1-f2));
                    ViewUtils.setTextViewStr(m_bishangci_tv,getFuHao(r1)+r1+" °F");
                }
            }
            lastTemMesureResult2_ewen = result;
        }
       // disButtomShowValue(result);
    }



    private int startPage;
    private void getButtomValue(){
        if (!NetUtils.available()){
            return;
        }
        LogUtils.i(TAG,"-MainActivity-getButtomValue-开始获取后台数据");
        //{"startIndex":1,"pageSize":50,"userId":10000004013}
        //{"resultCode":0,"resultMessage":"请求成功","resultData":{"count":37,"data":[]}}
        TGNetUtils.getInstance().getTempertureData13(this, TemUtils.getUerID(), startPage,
                50, new HttpResponse<GetTempertureData>() {
            @Override
            public void result(boolean isRequestSuccess, String requestDes, GetTempertureData getTempertureData, String s) {
                LogUtils.i(TAG,"-MainActivity-getButtomValue-getTempertureData1-s="+s);
                if (isRequestSuccess&&getTempertureData!=null&&getTempertureData.getResultData()!=null
                        &&getTempertureData.getResultData().getData()!=null
                        &&getTempertureData.getResultData().getData().size()>0){
                    startPage++;
                    //成功
                    if (mMainHisLvAdapter!=null){
                        mMainHisLvAdapter.addDatas(getTempertureData.getResultData().getData());
                        if (mMainHisLvAdapter.getCount()>0){
                            ViewUtils.goneView(main_norecord_tv);
                        }
                    }
                }else if (isRequestSuccess&&getTempertureData!=null&&getTempertureData.getResultData()!=null
                        &&getTempertureData.getResultData().getData()!=null
                        &&getTempertureData.getResultData().getData().size()==0){
                    //说明没有数据了 显示底部加载提示语

                    if (mMainHisLvAdapter!=null&&mMainHisLvAdapter.getCount()>0){
                        ViewUtils.displayView(nomore_tv);
                    }

                }

            }
        });

    }

    public void resetHisLvAdater(){
        startPage=0;
        if (mMainHisLvAdapter!=null){
            mMainHisLvAdapter.setDatas(null);
        }
    }





    //显示底部的值
    private void disButtomShowValue(TemMesureResult2 result) {
//        if (TAppConfig.isVisitorModel){
//            return;
//        }
        ViewUtils.hideView(main_norecord_tv);
        //00：耳温C标记
        //01：耳温F标记
        //02：额温C标记
        //03：额温F标记
        GetTempertureData.ResultDataBean.DataBean dataBean = new GetTempertureData.ResultDataBean.DataBean();
        //(1:耳温,2:额温)
        if (result.com == 0||result.com == 1){
            dataBean.tempType=1;
        }else {
            dataBean.tempType=2;
        }
        dataBean.setTemperature(result.temperature);
        dataBean.testDate=result.measureTimeStr;

        if (mMainHisLvAdapter!=null){
            mMainHisLvAdapter.addData(0,dataBean);
            if (mMainHisLvAdapter.getCount()>0){
                ViewUtils.goneView(main_norecord_tv);
            }else {
                ViewUtils.displayView(main_norecord_tv);
            }
        }





    }

    private void registerReceiver() {
        myReceiver = new MyReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_TIME_TICK);
        registerReceiver(myReceiver,filter);
    }

    //显示用户名
    private void disUserName() {
        if (TAppConfig.isVisitorModel) {
            //访客
            ViewUtils.setTextViewStr(main_login_userName_tv, "访客");
        } else {
            String userName = TemUtils.getUerNickName();
            ViewUtils.setTextViewStr(main_login_userName_tv, userName);
        }
    }

    @Override
    protected boolean isInitMainBaseHandle() {
        return true;
    }

    @Override
    protected void activityHandleMsg(Message msg) {

    }


    //打开设置界面
    public void go2setting(View view) {

        if (TAppConfig.isVisitorModel){
            ToastUtil.show(R.string.fkbyxjr);
            return;
        }
        startActivity(SettingActivity.class,null);
    }

    //打开体温曲线
    public void go2qushi(View view) {

        if (TAppConfig.isVisitorModel){
            ToastUtil.show(R.string.fkbyxjr);
            return;
        }

        startActivity(TemperatureCurveActivity.class,null);
    }

    //添加温度
    public void addTem(View view) {
        if (TAppConfig.isVisitorModel){
            ToastUtil.show(R.string.fkbyxjr);
            return;
        }
        Intent intent=new Intent(this,AddTemperatureActivity.class);
        startActivityForResult(intent,AddTemperatureActivity.REQUEST_CODE);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        BlueManager.getInstance().removeBluetoothStationListener(mIBlueStationListener);
        mIBlueStationListener=null;
        if (myReceiver!=null){
            unregisterReceiver(myReceiver);
        }
        if (mTgManager!=null){
            mTgManager.exitTgManager();
            mTgManager=null;
        }
    }



    //用户切换按钮
    public void main_login_user_rl(View view) {

        Intent intent = new Intent(this,PeopleChooseActivity.class);
        startActivityForResult(intent,PeopleChooseActivity.REQUEST_CODE);


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.m_jqqsh_iv:
                m_jqqsh_iv_Click();
                break;
        }
    }

    //近期趋势按钮被点击
    private void m_jqqsh_iv_Click() {
        if (TAppConfig.isVisitorModel){
            LogUtils.i(TAG,"访客模式 近期趋势按钮不可点击");
        }
    }

    private class MyReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
             if (Intent.ACTION_TIME_TICK.equals(action)) {
                 timeChange();//时间改变
             }
        }
    }

    //时间改变
    private void timeChange() {
        LogUtils.i(TAG,"----timeChange---");
        String time = TimeUtils.formatTime22(System.currentTimeMillis());
        ViewUtils.setTextViewStr(main_time_tv,time);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PeopleChooseActivity.REQUEST_CODE && resultCode == PeopleChooseActivity.RESULT_CODE){
            LogUtils.i(TAG,"人物选择 界面刚退出");
            dealUserSwit(data);
        }else if (requestCode == AddTemperatureActivity.REQUEST_CODE && resultCode == AddTemperatureActivity.RESULT_CODE){
            LogUtils.i(TAG,"添加温度 界面刚退出");
            resetHisLvAdater();
            getButtomValue();
        }


    }


    //处理人物选择界面退出来的事务
    private void dealUserSwit(Intent data) {
        boolean isChange = data.getBooleanExtra(PeopleChooseActivity.IsChange, false);
        LogUtils.i(TAG,"---------isChange = " + isChange);
        if (isChange){
            disUserName(); //显示用户名

            ViewUtils.setTextViewStr(m_mesure_station_tv,"--");//测量状态
            ViewUtils.setTextViewStr(m_bishangci_tv,"--");//比上次


            if (mMainHisLvAdapter!=null){
                mMainHisLvAdapter.setDatas(null);
                if (mMainHisLvAdapter.getCount()>0){
                    ViewUtils.goneView(main_norecord_tv);
                }else {
                    ViewUtils.displayView(main_norecord_tv);
                }
            }

            if (TAppConfig.isVisitorModel){
                lastTemMesureResult2_erwen=null;
                lastTemMesureResult2_ewen=null;
                ViewUtils.goneView(main_norecord_tv);
            }

            if (!TAppConfig.isVisitorModel){
                startPage=0;
                getButtomValue();
            }


        }
    }



    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(CommonEventBus event) {
        if (!event.whichReceive.contains(TAG)) {
            return;
        }
        LogUtils.i(TAG, "MainActivity--onEventMainThread接收到CommonEventBus信息--" + event.toString());


        if (event.cmd == UnitSwitchActivity.CHANGE){
            willUnit = (int) event.getContent();

            if (mMainHisLvAdapter!=null){
                mMainHisLvAdapter.updateUnit();
            }
            LogUtils.i(TAG, "MainActivity--onEventMainThread---接收到下发单位给称的指令");
            sendUnit2Scale(willUnit);
        }else if (event.cmd == TgUpLoadDataUtil.UPLOADSUCCESS){
            LogUtils.i(TAG, "MainActivity--onEventMainThread---接收到上传数据成功--重新拉取一遍列表");
            if (!NetUtils.available()){
                return;
            }
            startPage=0;
            if (mMainHisLvAdapter!=null)mMainHisLvAdapter.setDatas(null);


            getButtomValue();
        }else if (event.cmd == ModifyNameActivity.ModifyName_Success){
            disUserName();
        }



    }
    private int willUnit;
    //发送单位到
    private void sendUnit2Scale(int unit) {

       // UserSpUtil.writeInt(IConstant.IUserSpCon.UNIT,unit);
        if (mTgManager==null){
            return;
        }
        if (mTgManager.isConnect()){
            willUnit=unit;
            LogUtils.i(TAG,"下发了单位信息给秤--设置单位 unit="+unit);
            if (unit==0){
                if (mTgManager!=null)mTgManager.setUnitC();
            }else {
                if (mTgManager!=null)mTgManager.setUnitF();
            }
        }


    }
}
